/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 9/25/12
 * Time: 10:42 PM
 * To change this template use File | Settings | File Templates.
 */
package vplib.maple {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;

import mx.rpc.xml.SchemaTypeRegistry;

import vplib.component.AbstractPhysicsComponent;
import vplib.component.IPhysicsComponent;

import vplib.lab.Lab;
import vplib.model.PhysicsProperty;

public class MapleCodeAccess {
    private var fileName:String;
    private var dataFromFile:String;
    private var _eventDispatcher:EventDispatcher;

    public function MapleCodeAccess(file:String) {
        this.fileName = file;
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, onLoaded);
        loader.load(new URLRequest(this.fileName));
        trace("[PropertyAccess] - Loading data from file '" + this.fileName + "'.");
    }

    private function onLoaded(e:Event):void {
        this.dataFromFile = e.target.data;
        _eventDispatcher.dispatchEvent(new Event(Event.COMPLETE));
        trace("[PropertyAccess] - Load data from file '" + this.fileName + "'. \n\tData: " + e.target.data);
    }

    public static function createMapleCode(fileName:String, lab:Lab):void {
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, function (event:Event):void {
            var result:String = event.target.data;
            const dataFromFile:String = event.target.data;

            result = LikeVelocityUtil.setVariable(result, "countCalc", (200).toString());

            var variables:String = "";
            var fields:String = "";
            for each (var comp:IPhysicsComponent in lab.physicsComponents) {
                for each (var prop:PhysicsProperty in comp.getModel().properties) {
                    variables += LikeVelocityUtil.createAndInitializeVariable(comp.getUniqueId(), prop) + ":\n";

                    if (prop.buildField)
                        fields += LikeVelocityUtil.createAndInitializeVariableField(comp.getUniqueId(), prop) + ":\n";
                }
            }
            result = LikeVelocityUtil.setVariable(result, "created_variables", variables);
            result = LikeVelocityUtil.setVariable(result, "return_variables", fields);
            result = LikeVelocityUtil.setVariable(result, "body_change_var_1", "HELLO_WORLD");

        });

        try {
            loader.load(new URLRequest("form_lab_code.txt"));
        } catch (error:Error) {
            trace(error.message);
        }
    }
}
}
